<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/" class="search-form">
      <van-search
        @cancel="onCancel"
        @focus="isResultShow=false"
        @search="onSearch"
        autofocus
        background="#2396fa"
        placeholder="请输入搜索关键词"
        show-action
        v-model="searchText"
      />
    </form>
    <!-- 、搜索栏 -->

    <!-- 搜索结果 -->
    <search-result :search-text="searchText" v-if="isResultShow"></search-result>

    <!-- 联想建议 -->
    <search-suggest :searchText="searchText" @search="onSearch" v-else-if="searchText"></search-suggest>

    <!-- 搜索历史记录 -->
    <search-history
      :search-histories="SearchHistories"
      @clear-all-histories="SearchHistories=[]"
      @search="onSearch"
      v-else
    ></search-history>
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggest from './components/search-suggest.vue'
import SearchResult from './components/search-result.vue'
import { setItem, getItem } from '@/utils/storage'


export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggest,
    SearchResult
  },
  data () {
    return {
      searchText: "",
      isResultShow: false,
      SearchHistories: getItem("TOUTIAO_SEARCH_HISTORIES") || []
    }
  },
  watch: {
    SearchHistories: function (value) {
      setItem('TOUTIAO_SEARCH_HISTORIES', value)
    }
  },
  methods: {
    onSearch (val) {
      this.searchText = val
      // 存储搜索历史记录
      // 要求：不要有重复历史记录、最新的排在最前面
      const index = this.SearchHistories.indexOf(val)
      if (index === -1) {
        this.SearchHistories.unshift(val)
      }

      // 渲染搜索结果
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    }
  },
}
</script>

<style lang="less" scoped>
.van-search__action {
  color: #fff;
}
.search-form {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1;
}
.search-container {
  padding-top: 108px;
}
.search-result {
  overflow-y: auto;
  height: 88vh;
}
</style>